<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Goods\Repository;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query\Expr\Join;
use Goods\Entity\Goods;
use Goods\Entity\GoodsGroupPrice;
use Goods\Entity\GoodsImage;
use Goods\Entity\GoodsSalesRecord;
use Goods\Entity\GoodsSpecTagGoods;

class GoodsSpecTagGoodsRepository extends EntityRepository
{
    /**
     * 通过特定标签和模板检索商品
     * @param $specTagCode
     * @param $templateCode
     * @param $userGroupId
     * @return int|mixed|string
     */
    public function findSpecTagGoodsByTagAndTemplate($specTagCode, $templateCode, $userGroupId)
    {
        $query = $this->getEntityManager()->createQueryBuilder()
            ->select('s',
                'g.goodsName','g.virtualSales', 'g.classId', 'g.goodsPrice', 'g.goodsMarketPrice', 'g.goodsWeight', 'g.goodsWeightUnit', 'g.goodsDescription',
                'i.goodsThumbnailImage',
                'r.goodsSalesNum'
            )
            ->from(GoodsSpecTagGoods::class, 's')
            ->innerJoin(Goods::class, 'g', Join::WITH, 'g.goodsId = s.goodsId')
            ->innerJoin(GoodsSalesRecord::class, 'r', Join::WITH, 'g.goodsId =  r.goodsId')
            ->leftJoin(GoodsImage::class, 'i', Join::WITH, 'g.goodsImageId = i.goodsImageId')
            ->where('s.specTagCode = :specTagCode')->setParameter('specTagCode', $specTagCode)
            ->andWhere('s.templateCode = :templateCode')->setParameter('templateCode', $templateCode)
            ->andWhere('g.goodsState=1')
            ->orderBy('s.specTagGoodsSort', 'ASC')
            ->addOrderBy('s.goodsId', 'DESC');

        //如果会员组存在，则获取会员组价格
        if($userGroupId > 0) $query->addSelect('(SELECT p.userGroupPrice FROM '.GoodsGroupPrice::class.' AS p WHERE p.goodsId=g.goodsId AND p.userGroupId='.$userGroupId.') AS goodsGroupPrice');

        return $query->getQuery()->getResult();
    }

    /**
     * 特定标签商品
     * @param $specTagId
     * @return mixed
     */
    public function findSpecTagGoods($specTagId)
    {
        $query = $this->getEntityManager()->createQueryBuilder()
            ->select('s', 'g.goodsName', 'g.goodsState')
            ->from(GoodsSpecTagGoods::class, 's')
            ->innerJoin(Goods::class, 'g', Join::WITH, 'g.goodsId = s.goodsId')
            ->where('s.specTagId = :specTagId')->setParameter('specTagId', $specTagId)
            ->orderBy('s.specTagGoodsSort', 'ASC')
            ->addOrderBy('s.goodsId', 'DESC');

        return $query->getQuery()->getResult();
    }
}